package com.industrial.operation.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.StringUtils;
import com.industrial.common.core.utils.DateUtils;
import com.industrial.common.core.web.domain.AjaxResult;
import com.industrial.common.security.utils.SecurityUtils;
import com.industrial.operation.domain.OperationCityCheck;
import com.industrial.operation.mapper.OperationCityCheckMapper;
import com.industrial.operation.service.IOperationCityCheckService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class OperationCityCheckServiceImpl implements IOperationCityCheckService {

    @Autowired
    private OperationCityCheckMapper operationCityCheckMapper;

    /**
     * 查询十六市地市考核
     *
     * @param baseId 十六市地市考核主键
     * @return 十六市地市考核
     */
    @Override
    public OperationCityCheck selectOperationCityCheckByBaseId(String baseId)
    {
        return operationCityCheckMapper.selectOperationCityCheckByBaseId(baseId);
    }

    /**
     * 查询十六市地市考核列表
     *
     * @param operationCityCheck 十六市地市考核
     * @return 十六市地市考核
     */
    @Override
    public List<OperationCityCheck> selectOperationCityCheckList(OperationCityCheck operationCityCheck)
    {
        return operationCityCheckMapper.selectOperationCityCheckList(operationCityCheck);
    }

    /**
     * 新增十六市地市考核
     *
     * @param operationCityCheck 十六市地市考核
     * @return 结果
     */
    @Override
    public int insertOperationCityCheck(OperationCityCheck operationCityCheck)
    {
        return operationCityCheckMapper.insertOperationCityCheck(operationCityCheck);
    }

    /**
     * 修改十六市地市考核
     *
     * @param operationCityCheck 十六市地市考核
     * @return 结果
     */
    @Override
    public int updateOperationCityCheck(OperationCityCheck operationCityCheck)
    {
        return operationCityCheckMapper.updateOperationCityCheck(operationCityCheck);
    }

    /**
     * 批量删除十六市地市考核
     *
     * @param baseIds 需要删除的十六市地市考核主键
     * @return 结果
     */
    @Override
    public int deleteOperationCityCheckByBaseIds(String[] baseIds)
    {
        return operationCityCheckMapper.deleteOperationCityCheckByBaseIds(baseIds);
    }

    /**
     * 删除十六市地市考核信息
     *
     * @param baseId 十六市地市考核主键
     * @return 结果
     */
    @Override
    public int deleteOperationCityCheckByBaseId(String baseId)
    {
        return operationCityCheckMapper.deleteOperationCityCheckByBaseId(baseId);
    }

    /**
     * 导入数据
     *
     * @param file
     * @param years
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult importCityCheckInfo(MultipartFile file, String years) {
        //获取当前操作人ID
        String operationUserId = SecurityUtils.getUserId();

        try{
           List<OperationCityCheck> readList = EasyExcel.read(file.getInputStream()).head(OperationCityCheck.class).headRowNumber(2).sheet().doReadSync();

           List<OperationCityCheck> list = new ArrayList<>();

           for(OperationCityCheck t : readList){
                //设置一些基本信息 Id、创建时间、更新时间、创建人、更新人
               t.setYears(years);
               t.setBaseId(IdUtil.simpleUUID());
               t.setBaseCreateBy(operationUserId);
               t.setBaseCreateTime(DateUtils.getNowDate());
               t.setBaseUpdateBy(operationUserId);
               t.setBaseUpdateTime(DateUtils.getNowDate());
               list.add(t);

               //每100条入库一次
               if(list.size() >= 100){
                   operationCityCheckMapper.batchInsertOperationCityCheck(list);
                   list.clear();
               }
           }

           //如果for完成集合不是空，再次插入数据
           if(!list.isEmpty()){
               operationCityCheckMapper.batchInsertOperationCityCheck(list);
               list.clear();
           }
           return AjaxResult.success("导入成功");
       }catch (Exception e){
          e.printStackTrace();
          return AjaxResult.warn("导入失败");
       }
    }

    /**
     * 查询十六市考核排名
     *
     * @param params
     * @return
     */
    @Override
    public Map<String,List<String>> cityCheckOrder(OperationCityCheck params) {
        List<OperationCityCheck> list = operationCityCheckMapper.cityCheckOrder(params);
        List<String> xAxis = new ArrayList<>();
        List<String> yAxis = new ArrayList<>();

        for(OperationCityCheck temp : list){
            String cityCode = temp.getCityCode();
            String evaluationScore = temp.getEvaluationScore();

            xAxis.add(cityCode);
            yAxis.add(evaluationScore);
        }

        Map<String,List<String>> resultMap = new HashMap<>(16);
        resultMap.put("xAxis",xAxis);
        resultMap.put("yAxis",yAxis);
        return resultMap;
    }

    /**
     * 十六地市指标统计
     *
     * @param params
     * @return
     */
    @Override
    public Map<String,List<String>> cityIndexCheckOrder(OperationCityCheck params) {
        List<OperationCityCheck> operationCityChecks = operationCityCheckMapper.cityIndexCheckOrder(params);
        List<String> xAxis = new ArrayList<>();
        List<String> yAxis = new ArrayList<>();

        for(OperationCityCheck temp : operationCityChecks){
            String cityCode = temp.getCityCode();
            String resultValue = temp.getResultValue();

            xAxis.add(cityCode);
            yAxis.add(resultValue);
        }

        Map<String,List<String>> resultMap = new HashMap<>(16);
        resultMap.put("xAxis",xAxis);
        resultMap.put("yAxis",yAxis);
        return resultMap;
    }

    /**
     * 十六市历年考核评价得分趋势
     *
     * @param params
     * @return
     */
    @Override
    public Map<String,Object> cityJnScroe(OperationCityCheck params) {

        String years = params.getYears();
        Integer endYear = Integer.valueOf(params.getYears()) - 5;
        params.setEndYears(String.valueOf(endYear));
        params.setStartYears(years);

        List<OperationCityCheck> operationCityChecks = operationCityCheckMapper.cityJnScroe(params);


        List<String> xAxis = new ArrayList<>();
        List<String> tl = new ArrayList<>();

        for(int i = Integer.valueOf(params.getEndYears()); i <=  Integer.valueOf(params.getStartYears());i++){
            xAxis.add(String.valueOf(i));
        }

        Map<String,List<String>> r = new LinkedHashMap<>(16);

        Map<String, List<OperationCityCheck>> resultDataMap = new HashMap<>(16);
        if(operationCityChecks != null && !operationCityChecks.isEmpty()){
            resultDataMap = operationCityChecks.stream().collect(Collectors.groupingBy(OperationCityCheck::getYears));
            List<String> cityCodeArgs = operationCityChecks.stream().map(OperationCityCheck::getCityCode).collect(Collectors.toList());
            for(String cityCode : cityCodeArgs){
                r.put(cityCode,new ArrayList<>());
            }
        }



        for(String year : xAxis){
            List<OperationCityCheck> cacheData = resultDataMap.get(year);
            if(cacheData != null){

                //取出数组中的城市名称
                List<String> cacheCityCode = cacheData.stream().map(OperationCityCheck::getCityCode).collect(Collectors.toList());
                for(Map.Entry<String, List<String>> p : r.entrySet()){
                    String key = p.getKey();
                    if(!ArrayUtil.contains(cacheCityCode.toArray(),key)){
                        List<String> value = p.getValue();
                        value.add("0");
                    }
                }

                for(OperationCityCheck p : cacheData){
                    String cityCode = p.getCityCode();
                    if(!r.containsKey(cityCode)){
                        List<String> t = new ArrayList<>();
                        r.put(cityCode,t);
                    }
                    List<String> strings = r.get(cityCode);
                    strings.add(StringUtils.isBlank(p.getEvaluationScore()) ? "0" : p.getEvaluationScore());
                }
            }else{
                for(Map.Entry<String, List<String>> p : r.entrySet()){
                    List<String> value = p.getValue();
                    value.add("0");
                }
            }
        }

        List<List<String>> resultList = new ArrayList<>();

        for(Map.Entry<String,List<String>> pp : r.entrySet()){
            String key = pp.getKey();
            tl.add(key);
            resultList.add(pp.getValue());
        }

        Map<String,Object> resultMap = new HashMap<>(16);
        resultMap.put("x",xAxis);
        resultMap.put("tl",tl);
        resultMap.put("args",resultList);
        return resultMap;
    }
}
